package com.colter.project.sample.thread.part06.test1;

import java.util.Date;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

//阻塞式线程安全列表 LinkedBlockingDeque
public class Test3 {
	public static void main(String[] args) {
		LinkedBlockingDeque<String> list = new LinkedBlockingDeque<>();
		Client client = new Client(list);
		Thread thread = new Thread(client);
		thread.start();

		for (int i = 0; i < 3; i++) {
			for (int j = 0; j < 5; j++) {
				try {
					String request = list.take();
					System.out.println("Main:Request:Take:" + request + " " + new Date() + " " + list.size());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			try {
				TimeUnit.MICROSECONDS.sleep(300);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		System.out.println("Main:End");
	}
}

class Client implements Runnable {

	private LinkedBlockingDeque<String> requestList;

	public Client(LinkedBlockingDeque<String> requestList) {
		super();
		this.requestList = requestList;
	}

	@Override
	public void run() {
		for (int i = 0; i < 3; i++) {
			for (int j = 0; j < 5; j++) {
				StringBuilder sb = new StringBuilder();
				sb.append(i);
				sb.append(":");
				sb.append(j);

				try {
					requestList.put(sb.toString());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("Client:" + sb + " " + new Date());

			}

			try {
				TimeUnit.SECONDS.sleep(2);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		System.out.println("Client: End");
	}

}
